﻿using JTG.ServiceInterface.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Xml;
using Tzw.Common;

namespace JTG.ServiceInterface.InterfaceService
{
    /// <summary>
    /// 资中中医院
    /// </summary>
    public class ZzzyyService
    {
        string _jsonFile = "appsettings.json";
        string _key = "116D1A66F4439FDA";                           //秘钥
        private string _token = "658BD6F4C64D9C2FF6C7916414A57B2A"; //his提供的token
        string _transToken;                                         //传输用的token
        private string _jslb = "金泰格自助机";                            //结算类别
        string _apiUrl = "http://192.168.70.241:8086/ExternalServices/ZL_InformationService.asmx/USERMANAGER";

        public ZzzyyService()
        {
            //初始化配置信息
            _key = ConfigurationManager.AppSettings["key"] ?? "116D1A66F4439FDA";
            _token = ConfigurationManager.AppSettings["token"] ?? "658BD6F4C64D9C2FF6C7916414A57B2A";
            var baseUrl = ConfigurationManager.AppSettings["baseUrl"] ?? "http://192.168.70.241:8086";
            _apiUrl = baseUrl + "/ExternalServices/ZL_InformationService.asmx/";

            _transToken = Secret.Encrypt_AES(_token, _key);
        }

        /// <summary>
        /// 1通过健康卡查询病人信息
        /// </summary>
        /// <returns></returns>
        public string GetPatientIdByCardId(string cardId)
        {
            try
            {
                Logger.Default.Debug($"病人信息查询：<ZJKH>{cardId}</ZJKH><KLB>居民健康卡</KLB>");

                //请求内容
                var dataParam = Secret.Encrypt_AES($"<ZJKH>{cardId}</ZJKH><KLB>居民健康卡</KLB>", _key);

                //请求数据拼接
                var body = AggregatePara("BindCard.UserInfoByJZK.Query", _transToken, dataParam);

                //请求Neri
                var apiResult = SoapHelper.GetSoapReSource(_apiUrl + "Custom", body, "application/x-www-form-urlencoded");

                var doc = new XmlDocument();
                if (doc.GetCdData(apiResult, "ROOT/STATE") == "T")
                {
                    //获取密文
                    var secreteContent = doc.GetCdData(apiResult, "ROOT/DATAPARAM");

                    //密文解密
                    var content = Secret.Decrypt_AES(secreteContent, _key);

                    Logger.Default.Debug($"1通过健康卡查询病人信息-密文内容：{content}");

                    var xmlContent = new XmlDocument();
                    return xmlContent.GetCdData($"<ROOT>{content}</ROOT>", "ROOT/BRID");
                }

                Logger.Default.Error($"1通过健康卡查询病人信息接口请求失败：{apiResult}");
                return "";
            }
            catch (Exception e)
            {
                Logger.Default.Error($"查询病人信息异常：{e.Message}{e.StackTrace}");
                return "";
            }

        }

        /// <summary>
        /// 2获取检验报告列表
        /// </summary>
        /// <returns></returns>
        public List<ZzzyyReportInfo> LisReportQuery(string id)
        {
            try
            {
                Logger.Default.Debug($"报告列表请求ID：<BRID>{id}</BRID>");

                //请求内容
                var dataParam = Secret.Encrypt_AES($"<BRID>{id}</BRID>", _key);

                //请求数据拼接
                var body = AggregatePara("Zl.Third.JYBGLISTZZJ", _transToken, dataParam);

                var apiResult = SoapHelper.GetSoapReSource(_apiUrl + "Custom", body, "application/x-www-form-urlencoded");

                var doc = new XmlDocument();

                //获取密文
                var secreteContent = doc.GetCdData(apiResult, "ROOT/DATAPARAM");

                //密文解密
                var content = Secret.Decrypt_AES(secreteContent, _key);

                Logger.Default.Info($"报告列表返回内容：{content}");

                if (doc.GetCdData("ROOT/STATE") == "T")
                {
                    return XmlHelper.DeSerializer<ReportInfoRoot>($"<Root>{content}</Root>").LIST;
                }

                Logger.Default.Error($"2获取检验报告列表接口请求失败：{apiResult}");
                return new List<ZzzyyReportInfo>();
            }
            catch (Exception e)
            {
                Logger.Default.Error($"查询报告异常：{e.Message}{e.StackTrace}");
                return new List<ZzzyyReportInfo>();
            }
        }

        /// <summary>
        /// 3获取报告url
        /// </summary>
        /// <param name="yzid">医嘱id</param>
        /// <param name="brid">病人id</param>
        /// <returns></returns>
        public List<string> GetReportUrl(string yzid, string brid)
        {
            try
            {
                Logger.Default.Debug($"获取报告url：<YZID>{yzid}</YZID><BRID>{brid}</BRID>");

                //请求内容
                var dataParam = Secret.Encrypt_AES($"<YZID>{yzid}</YZID><BRID>{brid}</BRID>", _key);

                //请求数据拼接
                var body = AggregatePara("Zl.Third.BGPDFZZJ", _transToken, dataParam);

                var apiResult = SoapHelper.GetSoapReSource(_apiUrl + "Custom", body, "application/x-www-form-urlencoded");

                var doc = new XmlDocument();

                if (doc.GetCdData(apiResult, "ROOT/STATE") == "T")
                {
                    //获取密文
                    var secreteContent = doc.GetCdData("ROOT/DATAPARAM");

                    if (secreteContent.Equals("WKu3oyEYcDzMoJ/5kiXCYQ=="))
                    {
                        Logger.Default.Info($"没有获取到报告信息");
                        return new List<string>();
                    }

                    //密文解密
                    var content = Secret.Decrypt_AES(secreteContent, _key);

                    Logger.Default.Info($"获取报告url的返回内容：{content}");

                    return XmlHelper.DeSerializer<ZzzyyPdfs>(content).Pdfs;
                }

                Logger.Default.Error($"3获取报告url接口请求失败：{apiResult}");
                return new List<string>();
            }
            catch (Exception e)
            {
                Logger.Default.Error($"查询报告异常：{e.Message}{e.StackTrace}");
                return new List<string>();
            }

        }

        /// <summary>
        /// 4报告打印后回调
        /// </summary>
        /// <param name="brid"></param>
        /// <param name="ybtm"></param>
        public void LitPrintCallBack(string brid,string ybtm)
        {
            try
            {
                //请求内容
                var dataParam = Secret.Encrypt_AES($"<YBTM>{ybtm}</YBTM><BRID>{brid}</BRID><DAYC>1</DAYC>", _key);

                //请求数据拼接
                var body = AggregatePara("Zl.Third.BGDYCSZZJ", _transToken, dataParam);

                Logger.Default.Info("回写结果：" + SoapHelper.GetSoapReSource(_apiUrl + "Custom", body, "application/x-www-form-urlencoded"));
            }
            catch (Exception e)
            {
                Logger.Default.Error($"打印回调异常：{e.Message}{e.StackTrace}");
            }

        }


        /// <summary>
        /// 拼装要提交的数据
        /// </summary>
        /// <param name="service">服务器名称</param>
        /// <param name="token">令牌</param>
        /// <param name="dataParam">参数</param>
        /// <returns></returns>
        private string AggregatePara(string service, string token, string dataParam)
        {
            return "ReData=" + HttpUtility.UrlEncode(
                $"<ROOT><TOKEN><![CDATA[{token}]]></TOKEN><SERVICE><![CDATA[{service}]]></SERVICE><DATAPARAM><![CDATA[{dataParam}]]></DATAPARAM></ROOT>");
        }
    }
}


